﻿using AntdUI;
using BST250301.Models;
using BST250301TestStand.Models.Utils;
using Microsoft.IdentityModel.Logging;
using Microsoft.VisualBasic.ApplicationServices;
using MySql.Data.MySqlClient;
using Mysqlx;
using Mysqlx.Crud;
using NPOI.HSSF.Record;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using Org.BouncyCastle.Crypto.Generators;
using SkiaSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

using static System.ComponentModel.Design.ObjectSelectorEditor;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Menu;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace BST250301TestStand.Models
{
    internal static class DB
    {
        static internal AppConfig appconfig;
        public static int SetHashDate(string dthash, string username)
        {
            var user = new User();
            string sql = $"UPDATE `users` SET `AuthorizeHash`='{dthash}' WHERE  `Account` = '{username}'; ";
            return MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql);
        }
        public static Oper GetUserData(string db, string username)
        {
            var user = new Oper();
            string sql = $"SELECT * FROM `users` WHERE `Account` = '{username}' Limit 1; ";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(db, sql))
            {
                while (reader.Read())
                {
                    user.FullName = reader.GetString("FullName");
                    user.Password = reader.GetString("PasswordHash");
                    user.AuthorizeHash = reader.GetString("AuthorizeHash");
                    user.Account = reader.GetString("Account");
                    var ret = reader.GetInt16("OperLevel");
                    if (ret >= 90)
                        user.IsSuperAdmin = true;
                    if (ret >= 30)
                        user.DeleteEnable = true;
                    if (ret >= 20)
                        user.ModifyEnable = true;
                    if (ret >= 10)
                        user.OperEnable = true;
                    if (ret >= 0)
                        user.ViewEnable = true;
                    if (ret < 0)
                        user.ViewEnable = false;
                }
            }
            return user;
        }
        internal static int SetUserData(string username, string hashedpassword)
        {
            var user = new User();
            string sql = $"UPDATE `users` SET `PasswordHash`='{hashedpassword}' WHERE  `Account` = '{username}'; ";
            return MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql);
        }
        internal static AntList<ProjectItem> GetProjectNameList()
        {
            string sql = $"SELECT DISTINCT Name FROM testprojects  order by Name;";
            var list = new AntList<ProjectItem>();
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    list.Add(new ProjectItem
                    {
                        Name = reader.IsDBNull(reader.GetOrdinal("Name")) ? string.Empty : reader.GetString("Name"),
                        //TemplateName = reader.IsDBNull(reader.GetOrdinal("TemplateName")) ? string.Empty : reader.GetString("TemplateName"),
                        //PlanName = reader.IsDBNull(reader.GetOrdinal("PlanName")) ? string.Empty : reader.GetString("PlanName"),
                        //Description = reader.IsDBNull(reader.GetOrdinal("Description")) ? string.Empty : reader.GetString("Description"),
                        //Code = reader.IsDBNull(reader.GetOrdinal("Code")) ? string.Empty : reader.GetString("Code"),
                        //Note = reader.IsDBNull(reader.GetOrdinal("Mark")) ? string.Empty : reader.GetString("Mark"),
                        //ID = reader.IsDBNull(reader.GetOrdinal("id")) ? 0 : reader.GetInt16("id"),
                    });
                }
            }
            return list;
        }
        internal static bool SaveProject(ProjectItem item, string user)
        {
            try
            {
                string sql = $"INSERT INTO `testprojects` (`Name`, `Description`, `ConfirmWay`,`Code`, `TemperatureOil`, `CFStatus`, `CRStatus`, `CPTOStatus`, `MasterGearPosition`, `SlaveGearPosition`, `PTOGearPosition`,`LoadTorque`, `RotateSpeedStart`, `RotateSpeedEnd`, `RotateSpeedStep`, `RotateSpeedKeep`, `CFSetPointCurrentStart`, `CFSetPointCurrentEnd`, `CFSetPointCurrentStep`, `CFSetPointCurrentKeep`, `CRSetPointCurrentStart`, `CRSetPointCurrentEnd`, `CRSetPointCurrentStep`, `CRSetPointCurrentKeep`, `CPTOSetPointCurrentStart`, `CPTOSetPointCurrentEnd`, `CPTOSetPointCurrentStep`, `CPTOSetPointCurrentKeep`, `SetPointCurrentKPStartKeep`, `SetPointCurrentKPEndKeep`, `SetPointCurrentKPMaxOutSpeed`, `TestCondition`, `TestDuration`,`Times`, `Mark`) VALUES ('{item.Name}', '{item.Description}',{(int)item.ConfirmWay}, '{item.Code}',  {(int)item.TemperatureOil}, {(int)item.CFStatus}, {(int)item.CRStatus}, {(int)item.CPTOStatus}, {(int)item.MasterGearPosition}, {(int)item.SlaveGearPosition}, {(int)item.PTOGearPosition}, {item.LoadTorque}, {item.RotateSpeed.ValueStart},{item.RotateSpeed.ValueEnd},{item.RotateSpeed.StepValue},{item.RotateSpeed.StepKeep},{item.CFSetPointCurrent.ValueStart},{item.CFSetPointCurrent.ValueEnd},{item.CFSetPointCurrent.StepValue},{item.CFSetPointCurrent.StepKeep},{item.CRSetPointCurrent.ValueStart},{item.CRSetPointCurrent.ValueEnd},{item.CRSetPointCurrent.StepValue},{item.CRSetPointCurrent.StepKeep},{item.CPTOSetPointCurrent.ValueStart},{item.CPTOSetPointCurrent.ValueEnd},{item.CPTOSetPointCurrent.StepValue},{item.CPTOSetPointCurrent.StepKeep},{item.SetPointCurrentKP.KPEndKeep},{item.SetPointCurrentKP.StepKeep},{item.SetPointCurrentKP.KPMaxOutSpeed}, '{item.TestCondition}','{item.TestDuration}','{item.Times}', '{user}');\r\nSELECT LAST_INSERT_ID();";
                //INSERT INTO `transmission`.`testprojects` (`Name`, `Description`, `Code`, `TemperatureOil`, `SlaveGearPosition`, `RotateSpeedStart`, `RotateSpeedEnd`, `RotateSpeedStep`, `RotateSpeedKeep`, `CFSetPointCurrentStart`, `CFSetPointCurrentEnd`, `CFSetPointCurrentStep`, `CFSetPointCurrentKeep`, `CRSetPointCurrentStart`, `CRSetPointCurrentEnd`, `CRSetPointCurrentStep`, `CRSetPointCurrentKeep`, `CPTOSetPointCurrentStart`, `CPTOSetPointCurrentEnd`, `CPTOSetPointCurrentStep`, `CPTOSetPointCurrentKeep`, `TestCondition`, `Mark`) VALUES ('油温40离合分离挡位N转速300', '变速箱温度：40±3℃\r\n离合器状态：确认所有离合器为分离状态（CF、CR、CPTO）\r\n挡位状态：主副箱挡位均为空挡', '094cb62bca104752', 1, 2, 300, 400, 10, 5, 10, 100, 10, 9, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', 'admin');
                //`CFSetPointCurrentMode`={item.CFSetPointCurrent.SPCMode},`CFSetPointCurrentRepeat`={item.CFSetPointCurrent.Repeat},`SetPointCurrentKPStartKeep`={item.SetPointCurrentKP.KPStartKeep}, `SetPointCurrentKPEndKeep`={item.SetPointCurrentKP.KPEndKeep}, `SetPointCurrentKPMaxOutSpeed`={item.SetPointCurrentKP.KPMaxOutSpeed},

                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql);
                return res > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"记录错误： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        internal static bool UpdateProject(ProjectItem item, string user)
        {
            try
            {
                string sql = $"UPDATE `testprojects` SET `Name`='{item.Name}', `Description`= '{item.Description}', `ConfirmWay`={(int)item.ConfirmWay}, `TemperatureOil`={(int)item.TemperatureOil}, `CFStatus`={(int)item.CFStatus}, `CRStatus`={(int)item.CRStatus}, `CPTOStatus`= {(int)item.CPTOStatus}, `MasterGearPosition`={(int)item.MasterGearPosition}, `SlaveGearPosition`={(int)item.SlaveGearPosition},`PTOGearPosition`={(int)item.PTOGearPosition},`LoadTorque`= {item.LoadTorque}," +
                        $" `RotateSpeedStart`= {item.RotateSpeed.ValueStart}, `RotateSpeedEnd`={item.RotateSpeed.ValueEnd}, `RotateSpeedStep`={item.RotateSpeed.StepValue}, `RotateSpeedKeep`={item.RotateSpeed.StepKeep}, " +
                        $"`CFSetPointCurrentStart`={item.CFSetPointCurrent.ValueStart}, `CFSetPointCurrentEnd`={item.CFSetPointCurrent.ValueEnd}, `CFSetPointCurrentStep`={item.CFSetPointCurrent.StepValue}, `CFSetPointCurrentKeep`={item.CFSetPointCurrent.StepKeep}, `CFSetPointCurrentMode`={item.CFSetPointCurrent.SPCMode},`CFSetPointCurrentRepeat`={item.CFSetPointCurrent.Repeat}," +
                        $" `CRSetPointCurrentStart`={item.CRSetPointCurrent.ValueStart}, `CRSetPointCurrentEnd`={item.CRSetPointCurrent.ValueEnd}, `CRSetPointCurrentStep`={item.CRSetPointCurrent.StepValue}, `CRSetPointCurrentKeep`={item.CRSetPointCurrent.StepKeep},`CRSetPointCurrentMode`={item.CRSetPointCurrent.SPCMode},`CRSetPointCurrentRepeat`={item.CRSetPointCurrent.Repeat}," +
                        $" `CPTOSetPointCurrentStart`={item.CPTOSetPointCurrent.ValueStart}, `CPTOSetPointCurrentEnd`={item.CPTOSetPointCurrent.ValueEnd}, `CPTOSetPointCurrentStep`={item.CPTOSetPointCurrent.StepValue}, `CPTOSetPointCurrentKeep`={item.CPTOSetPointCurrent.StepKeep},`CPTOSetPointCurrentMode`={item.CPTOSetPointCurrent.SPCMode},`CPTOSetPointCurrentRepeat`={item.CPTOSetPointCurrent.Repeat}," +
                        $" `SetPointCurrentKPStartKeep`={item.SetPointCurrentKP.KPStartKeep}, `SetPointCurrentKPEndKeep`={item.SetPointCurrentKP.KPEndKeep}, `SetPointCurrentKPMaxOutSpeed`={item.SetPointCurrentKP.KPMaxOutSpeed}," +
                        $" `TestCondition`= '{item.TestCondition}',`TestDuration`= '{item.TestDuration}',`Times`= '{item.Times}', `Mark`='{user}'" +
                        $" WHERE `Code`='{item.Code}';\r\nSELECT LAST_INSERT_ID();";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql);
                return res > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"记录错误： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        internal static AntList<ProjectItem> GetProjectList(string name)
        {
            string sql = $"SELECT * FROM testprojects WHERE Name = '{name}'  order by Code;";

            var list = new AntList<ProjectItem>();
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    list.Add(new ProjectItem
                    {
                        Name = reader.IsDBNull(reader.GetOrdinal("Name")) ? string.Empty : reader.GetString("Name"),
                        Description = reader.IsDBNull(reader.GetOrdinal("Description")) ? string.Empty : reader.GetString("Description"),
                        ConfirmWay = (ConfWay)(reader.IsDBNull(reader.GetOrdinal("ConfirmWay")) ? 0 : reader.GetInt16("ConfirmWay")),
                        TestDuration = reader.IsDBNull(reader.GetOrdinal("TestDuration")) ? 0 : reader.GetInt16("TestDuration"),
                        Times = reader.IsDBNull(reader.GetOrdinal("Times")) ? 0 : reader.GetInt16("Times"),
                        Code = reader.IsDBNull(reader.GetOrdinal("Code")) ? string.Empty : reader.GetString("Code"),
                        Mark = reader.IsDBNull(reader.GetOrdinal("Mark")) ? string.Empty : reader.GetString("Mark"),
                        ID = reader.IsDBNull(reader.GetOrdinal("id")) ? 0 : reader.GetInt16("id"),
                        TemperatureOil = (TOil)(reader.IsDBNull(reader.GetOrdinal("TemperatureOil")) ? 0 : reader.GetInt16("TemperatureOil")),
                        CFStatus = (ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CFStatus")) ? 0 : reader.GetInt16("CFStatus")),
                        CRStatus = (ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CRStatus")) ? 0 : reader.GetInt16("CRStatus")),
                        CPTOStatus = (ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CPTOStatus")) ? 0 : reader.GetInt16("CPTOStatus")),
                        MasterGearPosition = (GearM)(reader.IsDBNull(reader.GetOrdinal("MasterGearPosition")) ? 0 : reader.GetInt16("MasterGearPosition")),
                        SlaveGearPosition = (GearS)(reader.IsDBNull(reader.GetOrdinal("SlaveGearPosition")) ? 0 : reader.GetInt16("SlaveGearPosition")),
                        PTOGearPosition = (GearPTO)(reader.IsDBNull(reader.GetOrdinal("PTOGearPosition")) ? 0 : reader.GetInt16("PTOGearPosition")),
                        LoadTorque = reader.IsDBNull(reader.GetOrdinal("LoadTorque")) ? 0 : reader.GetInt16("LoadTorque"),
                        RotateSpeed = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("RotateSpeedStart")) ? 0 : reader.GetInt16("RotateSpeedStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("RotateSpeedEnd")) ? 0 : reader.GetInt16("RotateSpeedEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("RotateSpeedStep")) ? 0 : reader.GetInt16("RotateSpeedStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("RotateSpeedKeep")) ? 0 : reader.GetInt16("RotateSpeedKeep"),
                        },
                        CFSetPointCurrent = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentStart")) ? 0 : reader.GetInt16("CFSetPointCurrentStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentEnd")) ? 0 : reader.GetInt16("CFSetPointCurrentEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentStep")) ? 0 : reader.GetInt16("CFSetPointCurrentStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentKeep")) ? 0 : reader.GetInt16("CFSetPointCurrentKeep"),
                            SPCMode = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentMode")) ? 0 : reader.GetInt16("CFSetPointCurrentMode"),
                            Repeat = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentRepeat")) ? 0 : reader.GetInt16("CFSetPointCurrentRepeat"),
                        },
                        CRSetPointCurrent = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentStart")) ? 0 : reader.GetInt16("CRSetPointCurrentStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentEnd")) ? 0 : reader.GetInt16("CRSetPointCurrentEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentStep")) ? 0 : reader.GetInt16("CRSetPointCurrentStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentKeep")) ? 0 : reader.GetInt16("CRSetPointCurrentKeep"),
                            SPCMode = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentMode")) ? 0 : reader.GetInt16("CRSetPointCurrentMode"),
                            Repeat = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentRepeat")) ? 0 : reader.GetInt16("CRSetPointCurrentRepeat"),
                        },
                        CPTOSetPointCurrent = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentStart")) ? 0 : reader.GetInt16("CPTOSetPointCurrentStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentEnd")) ? 0 : reader.GetInt16("CPTOSetPointCurrentEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentStep")) ? 0 : reader.GetInt16("CPTOSetPointCurrentStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentKeep")) ? 0 : reader.GetInt16("CPTOSetPointCurrentKeep"),
                            SPCMode = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentMode")) ? 0 : reader.GetInt16("CPTOSetPointCurrentMode"),
                            Repeat = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentRepeat")) ? 0 : reader.GetInt16("CPTOSetPointCurrentRepeat"),
                        },
                        SetPointCurrentKP=new StepTest
                        {
                            KPStartKeep = reader.IsDBNull(reader.GetOrdinal("SetPointCurrentKPStartKeep")) ? 0 : reader.GetInt16("SetPointCurrentKPStartKeep"),
                            KPEndKeep = reader.IsDBNull(reader.GetOrdinal("SetPointCurrentKPEndKeep")) ? 0 : reader.GetInt16("SetPointCurrentKPEndKeep"),
                            KPMaxOutSpeed = reader.IsDBNull(reader.GetOrdinal("SetPointCurrentKPMaxOutSpeed")) ? 0.0f : reader.GetFloat("SetPointCurrentKPMaxOutSpeed"),
                        },
                        TestCondition = reader.IsDBNull(reader.GetOrdinal("TestCondition")) ? string.Empty : reader.GetString("TestCondition"),
                        ListRecord = new List<RecordData>(),
                    });
                }
            }
            return list;
        }
        internal static RecordReport GetProjectListRecordReport(string code)
        {
            string sql = $"SELECT * FROM testprojects WHERE Code = '{code}'  order by Code;";

            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    return new RecordReport
                    {
                        ID = reader.IsDBNull(reader.GetOrdinal("id")) ? 0 : reader.GetInt16("id"),
                        ProjectName = reader.IsDBNull(reader.GetOrdinal("Name")) ? string.Empty : reader.GetString("Name"),
                        Desc = reader.IsDBNull(reader.GetOrdinal("Description")) ? string.Empty : reader.GetString("Description"),
                        Times = (reader.IsDBNull(reader.GetOrdinal("Times")) ? 0 : reader.GetInt16("Times")).ToString(),
                        ProjectCode = reader.IsDBNull(reader.GetOrdinal("Code")) ? string.Empty : reader.GetString("Code"),
                        OilSet = ((TOil)(reader.IsDBNull(reader.GetOrdinal("TemperatureOil")) ? 0 : reader.GetInt16("TemperatureOil"))).ToString(),
                        DriverSpeed = reader.IsDBNull(reader.GetOrdinal("RotateSpeedStart")) ? 0 : reader.GetInt16("RotateSpeedStart"),

                        CFStatusSet = ((ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CFStatus")) ? 0 : reader.GetInt16("CFStatus"))).ToString(),
                        CRStatusSet = ((ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CRStatus")) ? 0 : reader.GetInt16("CRStatus"))).ToString(),
                        CPTOStatusSet = ((ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CPTOStatus")) ? 0 : reader.GetInt16("CPTOStatus"))).ToString(),

                        GearM = ((GearM)(reader.IsDBNull(reader.GetOrdinal("MasterGearPosition")) ? 0 : reader.GetInt16("MasterGearPosition"))).ToString(),
                        GearS = ((GearS)(reader.IsDBNull(reader.GetOrdinal("SlaveGearPosition")) ? 0 : reader.GetInt16("SlaveGearPosition"))).ToString(),
                        GearPTO = ((GearPTO)(reader.IsDBNull(reader.GetOrdinal("PTOGearPosition")) ? 0 : reader.GetInt16("PTOGearPosition"))).ToString(),
                    };
                }
            }
            return null;
        }
        internal static ProjectItem GetProjectListByCode(string code)
        {
            string sql = $"SELECT * FROM testprojects WHERE Code = '{code}';";

            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    return new ProjectItem
                    {
                        Name = reader.IsDBNull(reader.GetOrdinal("Name")) ? string.Empty : reader.GetString("Name"),
                        Description = reader.IsDBNull(reader.GetOrdinal("Description")) ? string.Empty : reader.GetString("Description"),
                        ConfirmWay = (ConfWay)(reader.IsDBNull(reader.GetOrdinal("ConfirmWay")) ? 0 : reader.GetInt16("ConfirmWay")),
                        TestDuration = reader.IsDBNull(reader.GetOrdinal("TestDuration")) ? 0 : reader.GetInt16("TestDuration"),
                        Times = reader.IsDBNull(reader.GetOrdinal("Times")) ? 0 : reader.GetInt16("Times"),
                        Code = reader.IsDBNull(reader.GetOrdinal("Code")) ? string.Empty : reader.GetString("Code"),
                        Mark = reader.IsDBNull(reader.GetOrdinal("Mark")) ? string.Empty : reader.GetString("Mark"),
                        ID = reader.IsDBNull(reader.GetOrdinal("id")) ? 0 : reader.GetInt16("id"),
                        TemperatureOil = (TOil)(reader.IsDBNull(reader.GetOrdinal("TemperatureOil")) ? 0 : reader.GetInt16("TemperatureOil")),
                        CFStatus = (ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CFStatus")) ? 0 : reader.GetInt16("CFStatus")),
                        CRStatus = (ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CRStatus")) ? 0 : reader.GetInt16("CRStatus")),
                        CPTOStatus = (ClutchStatus)(reader.IsDBNull(reader.GetOrdinal("CPTOStatus")) ? 0 : reader.GetInt16("CPTOStatus")),
                        MasterGearPosition = (GearM)(reader.IsDBNull(reader.GetOrdinal("MasterGearPosition")) ? 0 : reader.GetInt16("MasterGearPosition")),
                        SlaveGearPosition = (GearS)(reader.IsDBNull(reader.GetOrdinal("SlaveGearPosition")) ? 0 : reader.GetInt16("SlaveGearPosition")),
                        PTOGearPosition = (GearPTO)(reader.IsDBNull(reader.GetOrdinal("PTOGearPosition")) ? 0 : reader.GetInt16("PTOGearPosition")),
                        LoadTorque = reader.IsDBNull(reader.GetOrdinal("LoadTorque")) ? 0 : reader.GetInt16("LoadTorque"),
                        RotateSpeed = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("RotateSpeedStart")) ? 0 : reader.GetInt16("RotateSpeedStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("RotateSpeedEnd")) ? 0 : reader.GetInt16("RotateSpeedEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("RotateSpeedStep")) ? 0 : reader.GetInt16("RotateSpeedStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("RotateSpeedKeep")) ? 0 : reader.GetInt16("RotateSpeedKeep"),
                        },
                        CFSetPointCurrent = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentStart")) ? 0 : reader.GetInt16("CFSetPointCurrentStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentEnd")) ? 0 : reader.GetInt16("CFSetPointCurrentEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentStep")) ? 0 : reader.GetInt16("CFSetPointCurrentStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentKeep")) ? 0 : reader.GetInt16("CFSetPointCurrentKeep"),
                            SPCMode = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentMode")) ? 0 : reader.GetInt16("CFSetPointCurrentMode"),
                            Repeat = reader.IsDBNull(reader.GetOrdinal("CFSetPointCurrentRepeat")) ? 0 : reader.GetInt16("CFSetPointCurrentRepeat"),
                        },
                        CRSetPointCurrent = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentStart")) ? 0 : reader.GetInt16("CRSetPointCurrentStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentEnd")) ? 0 : reader.GetInt16("CRSetPointCurrentEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentStep")) ? 0 : reader.GetInt16("CRSetPointCurrentStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentKeep")) ? 0 : reader.GetInt16("CRSetPointCurrentKeep"),
                            SPCMode = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentMode")) ? 0 : reader.GetInt16("CRSetPointCurrentMode"),
                            Repeat = reader.IsDBNull(reader.GetOrdinal("CRSetPointCurrentRepeat")) ? 0 : reader.GetInt16("CRSetPointCurrentRepeat"),
                        },
                        CPTOSetPointCurrent = new StepTest
                        {
                            ValueStart = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentStart")) ? 0 : reader.GetInt16("CPTOSetPointCurrentStart"),
                            ValueEnd = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentEnd")) ? 0 : reader.GetInt16("CPTOSetPointCurrentEnd"),
                            StepValue = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentStep")) ? 0 : reader.GetInt16("CPTOSetPointCurrentStep"),
                            StepKeep = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentKeep")) ? 0 : reader.GetInt16("CPTOSetPointCurrentKeep"),
                            SPCMode = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentMode")) ? 0 : reader.GetInt16("CPTOSetPointCurrentMode"),
                            Repeat = reader.IsDBNull(reader.GetOrdinal("CPTOSetPointCurrentRepeat")) ? 0 : reader.GetInt16("CPTOSetPointCurrentRepeat"),
                        },
                        SetPointCurrentKP = new StepTest
                        {
                            KPStartKeep = reader.IsDBNull(reader.GetOrdinal("SetPointCurrentKPStartKeep")) ? 0 : reader.GetInt16("SetPointCurrentKPStartKeep"),
                            KPEndKeep = reader.IsDBNull(reader.GetOrdinal("SetPointCurrentKPEndKeep")) ? 0 : reader.GetInt16("SetPointCurrentKPEndKeep"),
                            KPMaxOutSpeed = reader.IsDBNull(reader.GetOrdinal("SetPointCurrentKPMaxOutSpeed")) ? 0.0f : reader.GetFloat("SetPointCurrentKPMaxOutSpeed"),
                        },
                        TestCondition = reader.IsDBNull(reader.GetOrdinal("TestCondition")) ? string.Empty : reader.GetString("TestCondition"),
                        ListRecord = new List<RecordData>(),
                    };
                }
            }
            return null;
        }

        internal static AntList<TemplateItem> GetTestTemplate(string planname)
        {
            var list = new AntList<TemplateItem>();
            //string sql = $"SELECT * FROM testtemplates WHERE userid ='{user}' order by name;";
            string sql = $"SELECT * FROM testtemplates WHERE `PlanName` = '{planname}'  order by Name;";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    list.Add(new TemplateItem
                    {
                        PlanName = planname,
                        TestName = reader.IsDBNull(reader.GetOrdinal("Name")) ? string.Empty : reader.GetString("Name"),
                        Description = reader.IsDBNull(reader.GetOrdinal("Description")) ? string.Empty : reader.GetString("Description"),
                        UserId = reader.IsDBNull(reader.GetOrdinal("UserId")) ? string.Empty : reader.GetString("UserId"),
                        Repeat = reader.IsDBNull(reader.GetOrdinal("Repeat")) ? 0 : reader.GetInt16("Repeat"),
                        OrderID = reader.IsDBNull(reader.GetOrdinal("Id")) ? 0 : reader.GetInt16("Id"),
                        DT = reader.IsDBNull(reader.GetOrdinal("CreatedAt")) ? new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc) : reader.GetDateTime("CreatedAt"),
                    });
                }
            }
            return list;
        }
        /// <summary>
        /// 保存模板
        /// </summary>
        /// <param name="pemplatename">模板名称</param>
        /// <param name="user"></param>
        /// <returns></returns>
        internal static bool SaveTestTemplate(string planname, string templatename, string desc, int repeat, string user)
        {
            try
            {
                string sql2 = $"INSERT INTO `testtemplates` (`UserId`, `PlanName`, `Description`,`Name`,  `Repeat`, `CreatedAt`) VALUES ('{user}','{planname}','{desc}','{templatename}',{repeat},'{DateTime.Now}') ON DUPLICATE KEY UPDATE `Repeat`= {repeat},`CreatedAt`= '{DateTime.Now}';";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql2);
                return res > 0;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存测试模板名称错误,检查有无重复名称： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        internal static bool DeleteTestTemplate(string name, string planname)
        {
            try
            {
                //DELETE FROM `transmission`.`testtemplates` WHERE  `Id`=85;
                string sql2 = $"DELETE FROM `testtemplates` WHERE `PlanName` = '{planname}' and `Name` ='{name}';";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql2);
                return res > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除错误，请检查名称是否存在： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        internal static AntList<TemplateItem> GetPlanName(string db)
        {
            var list = new AntList<TemplateItem>();
            string sql = $"SELECT DISTINCT PlanName FROM templatesteps order by PlanName;";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(db, sql))
            {
                while (reader.Read())
                {
                    list.Add(new TemplateItem
                    {
                        PlanName = reader.IsDBNull(reader.GetOrdinal("PlanName")) ? string.Empty : reader.GetString("PlanName"),
                    });
                }
            }
            return list;
        }
        internal static AntList<TemplateItem> GetTemPlatestep(string planname, string name)
        {
            var list = new AntList<TemplateItem>();
            string sql = $"SELECT * FROM templatesteps WHERE `PlanName` ='{planname}' and TestTemplateId ='{name}' order by StepOrder;";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    list.Add(new TemplateItem
                    {
                        PlanName = planname,
                        TestName = reader.IsDBNull(reader.GetOrdinal("TestTemplateId")) ? string.Empty : reader.GetString("TestTemplateId"),
                        ProjectName = reader.IsDBNull(reader.GetOrdinal("TestProjectId")) ? string.Empty : reader.GetString("TestProjectId"),
                        ProjectCode = reader.IsDBNull(reader.GetOrdinal("ProjectCode")) ? string.Empty : reader.GetString("ProjectCode"),
                        OrderID = reader.IsDBNull(reader.GetOrdinal("StepOrder")) ? 0 : reader.GetInt16("StepOrder"),
                        UserId = reader.IsDBNull(reader.GetOrdinal("UserId")) ? string.Empty : reader.GetString("UserId"),
                        ItemType = (ProType)(reader.IsDBNull(reader.GetOrdinal("ItemType")) ? 0 : reader.GetInt16("ItemType")),
                        ConfirmWay = (ConfWay)(reader.IsDBNull(reader.GetOrdinal("ConfirmWay")) ? 0 : reader.GetInt16("ConfirmWay")),
                        PreDelay = reader.IsDBNull(reader.GetOrdinal("PreDelay")) ? 0 : reader.GetInt16("PreDelay"),
                        AfterDelay = reader.IsDBNull(reader.GetOrdinal("AfterDelay")) ? 0 : reader.GetInt16("AfterDelay"),
                        RecordData = reader.IsDBNull(reader.GetOrdinal("RecordData")) ? string.Empty : reader.GetString("RecordData"),
                    });
                }
            }
            return list;
        }
        internal static bool DelTemplateSteps(string templateid, string planname)
        {
            try
            {
                string sql = $"DELETE FROM `templatesteps` WHERE  `TestTemplateId`='{templateid}' and `PlanName` = '{planname}';";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql);
                return res > 0;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"记录错误： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        internal static bool SaveTemplateSteps(string planname, string templateid, AntList<ProjectItem> list, string user)
        {
            try
            {
                string subsql = "";
                foreach (var item in list)
                {
                    var recorddata = string.Join(";", item.ListRecordData == null ? new List<string>() : item.ListRecordData);
                    subsql += $"('{planname}','{templateid}','{item.Name}','{item.Code}','{item.OrderID}','{user}',{(int)item.ItemType},{(int)item.ConfirmWay},{item.PreDelay},{item.AfterDelay},'{recorddata}','{DateTime.Now}'),";
                }
                string sql2 = $"INSERT INTO `templatesteps` (`PlanName`,`TestTemplateId`, `TestProjectId`, `ProjectCode`, `StepOrder`, `UserId`,`ItemType`,`ConfirmWay`,`PreDelay`,`AfterDelay`,`RecordData`,`CreatedAt`) VALUES {subsql.TrimEnd(',')} ON DUPLICATE KEY UPDATE `CreatedAt`= '{DateTime.Now}';";

                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql2);
                return res > 0;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"记录错误： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        internal static bool UpdateTemplateStepsRecord(ProjectItem item)
        {
            try
            {
                var recorddata = string.Join(";", item.ListRecordData == null ? new List<string>() : item.ListRecordData);
                string sql = $"UPDATE `templatesteps` SET `RecordData`='{recorddata}' WHERE `ProjectCode`='{item.Code}'";

                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql);
                return res > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"记录错误： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        internal static AntList<AlarmItem> GetAlarmLog(DateTime? dtfrom, DateTime? dtto)
        {
            var list = new AntList<AlarmItem>();
            string sql = $"SELECT * FROM alarmlog WHERE CreatedAt >='{dtfrom}' and CreatedAt <='{dtto}' order by CreatedAt;";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    list.Add(new AlarmItem
                    {
                        ID = reader.IsDBNull(reader.GetOrdinal("Id")) ? 0 : reader.GetInt32("Id"),
                        Code = reader.IsDBNull(reader.GetOrdinal("Code")) ? string.Empty : reader.GetString("Code"),
                        ByEQ = reader.IsDBNull(reader.GetOrdinal("ByEQ")) ? string.Empty : reader.GetString("ByEQ"),
                        ResetState = reader.IsDBNull(reader.GetOrdinal("Reset")) ? 0 : reader.GetInt16("Reset"),
                        DTAlmarm = reader.IsDBNull(reader.GetOrdinal("CreatedAt")) ? new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc) : reader.GetDateTime("CreatedAt"),
                    });
                }
            }
            return list;
        }
        /// <summary>
        /// 获取所有记录数据参数
        /// </summary>
        /// <returns></returns>
        internal static List<RecordData> GetRecordData()
        {
            var list = new List<RecordData>();
            string sql = $"SELECT * FROM recordparameters;";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    float.TryParse(reader.IsDBNull(reader.GetOrdinal("StandardMax")) ? string.Empty : reader.GetString("StandardMax"), out float max);
                    float.TryParse(reader.IsDBNull(reader.GetOrdinal("StandardMin")) ? string.Empty : reader.GetString("StandardMin"), out float min);

                    list.Add(new RecordData
                    {
                        ID = reader.IsDBNull(reader.GetOrdinal("Id")) ? 0 : reader.GetInt32("Id"),
                        Name = reader.IsDBNull(reader.GetOrdinal("Name")) ? string.Empty : reader.GetString("Name"),
                        ReportName = reader.IsDBNull(reader.GetOrdinal("ReportName")) ? string.Empty : reader.GetString("ReportName"),
                        AppName = reader.IsDBNull(reader.GetOrdinal("AppName")) ? string.Empty : reader.GetString("AppName"),
                        Desc = reader.IsDBNull(reader.GetOrdinal("Desc")) ? string.Empty : reader.GetString("Desc"),
                        IsSystemData = reader.IsDBNull(reader.GetOrdinal("IsSystemData")) ? false : reader.GetInt16("IsSystemData") > 0,
                        DataRW = (RecordRW)(reader.IsDBNull(reader.GetOrdinal("DataRW")) ? 0 : reader.GetInt16("DataRW")),
                        DataFrom = (RecordFrom)(reader.IsDBNull(reader.GetOrdinal("DataFrom")) ? 0 : reader.GetInt16("DataFrom")),
                        DataAddr = reader.IsDBNull(reader.GetOrdinal("DataAddr")) ? string.Empty : reader.GetString("DataAddr"),
                        DataType = reader.IsDBNull(reader.GetOrdinal("DataType")) ? string.Empty : reader.GetString("DataType"),
                        DataStyle = (RecordStyle)(reader.IsDBNull(reader.GetOrdinal("DataStyle")) ? 0 : reader.GetInt16("DataStyle")),
                        DefaultValue = reader.IsDBNull(reader.GetOrdinal("DefaultValue")) ? string.Empty : reader.GetString("DefaultValue"),
                        StandardMax = max,
                        StandardMin = min,
                        Unit = reader.IsDBNull(reader.GetOrdinal("Unit")) ? string.Empty : reader.GetString("Unit"),
                    });
                }
            }
            return list;
        }
        internal static RecordData GetRecordDataByName(string name)
        {
            var list = new List<RecordData>();
            string sql = $"SELECT * FROM recordparameters where Name ='{name}';";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    float.TryParse(reader.IsDBNull(reader.GetOrdinal("StandardMax")) ? string.Empty : reader.GetString("StandardMax"), out float max);
                    float.TryParse(reader.IsDBNull(reader.GetOrdinal("StandardMin")) ? string.Empty : reader.GetString("StandardMin"), out float min);
                    return new RecordData
                    {
                        ID = reader.IsDBNull(reader.GetOrdinal("Id")) ? 0 : reader.GetInt32("Id"),
                        Name = name,
                        ReportName = reader.IsDBNull(reader.GetOrdinal("ReportName")) ? string.Empty : reader.GetString("ReportName"),
                        AppName = reader.IsDBNull(reader.GetOrdinal("AppName")) ? string.Empty : reader.GetString("AppName"),
                        DefaultValue = reader.IsDBNull(reader.GetOrdinal("DefaultValue")) ? string.Empty : reader.GetString("DefaultValue"),
                        StandardMax = max,
                        StandardMin = min,
                        SetValue = reader.IsDBNull(reader.GetOrdinal("SetValue")) ? string.Empty : reader.GetString("SetValue"),
                        Desc = reader.IsDBNull(reader.GetOrdinal("Desc")) ? string.Empty : reader.GetString("Desc"),
                        IsSystemData = reader.IsDBNull(reader.GetOrdinal("IsSystemData")) ? false : reader.GetInt16("IsSystemData") > 0,
                        DataRW = (RecordRW)(reader.IsDBNull(reader.GetOrdinal("DataRW")) ? 0 : reader.GetInt16("DataRW")),
                        DataFrom = (RecordFrom)(reader.IsDBNull(reader.GetOrdinal("DataFrom")) ? 0 : reader.GetInt16("DataFrom")),
                        DataAddr = reader.IsDBNull(reader.GetOrdinal("DataAddr")) ? string.Empty : reader.GetString("DataAddr"),
                        DataType = reader.IsDBNull(reader.GetOrdinal("DataType")) ? string.Empty : reader.GetString("DataType"),
                        DataStyle = (RecordStyle)(reader.IsDBNull(reader.GetOrdinal("DataStyle")) ? 0 : reader.GetInt16("DataStyle")),
                        Unit = reader.IsDBNull(reader.GetOrdinal("Unit")) ? string.Empty : reader.GetString("Unit"),
                    };
                }
            }
            return null;
        }
        /// <summary>
        /// 获取系统状态参数列表
        /// </summary>
        /// <returns></returns>
        internal static List<RecordData> GetSystemRecordData()
        {
            var list = new List<RecordData>();
            string sql = $"SELECT * FROM recordparameters where `IsSystemData` = 1;";
            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
            {
                while (reader.Read())
                {
                    float.TryParse(reader.IsDBNull(reader.GetOrdinal("StandardMax")) ? string.Empty : reader.GetString("StandardMax"), out float max);
                    float.TryParse(reader.IsDBNull(reader.GetOrdinal("StandardMin")) ? string.Empty : reader.GetString("StandardMin"), out float min);
                    list.Add(new RecordData
                    {
                        ID = reader.IsDBNull(reader.GetOrdinal("Id")) ? 0 : reader.GetInt32("Id"),
                        Name = reader.IsDBNull(reader.GetOrdinal("Name")) ? string.Empty : reader.GetString("Name"),
                        ReportName = reader.IsDBNull(reader.GetOrdinal("ReportName")) ? string.Empty : reader.GetString("ReportName"),
                        AppName = reader.IsDBNull(reader.GetOrdinal("AppName")) ? string.Empty : reader.GetString("AppName"),
                        Desc = reader.IsDBNull(reader.GetOrdinal("Desc")) ? string.Empty : reader.GetString("Desc"),
                        IsSystemData = reader.IsDBNull(reader.GetOrdinal("IsSystemData")) ? false : reader.GetInt16("IsSystemData") > 0,
                        DataRW = (RecordRW)(reader.IsDBNull(reader.GetOrdinal("DataRW")) ? 0 : reader.GetInt16("DataRW")),
                        DataFrom = (RecordFrom)(reader.IsDBNull(reader.GetOrdinal("DataFrom")) ? 0 : reader.GetInt16("DataFrom")),
                        DataAddr = reader.IsDBNull(reader.GetOrdinal("DataAddr")) ? string.Empty : reader.GetString("DataAddr"),
                        DataType = reader.IsDBNull(reader.GetOrdinal("DataType")) ? string.Empty : reader.GetString("DataType"),
                        DataStyle = (RecordStyle)(reader.IsDBNull(reader.GetOrdinal("DataStyle")) ? 0 : reader.GetInt16("DataStyle")),
                        ReadValue = reader.IsDBNull(reader.GetOrdinal("ReadValue")) ? string.Empty : reader.GetString("ReadValue"),
                        SetValue = reader.IsDBNull(reader.GetOrdinal("SetValue")) ? string.Empty : reader.GetString("SetValue"),
                        DefaultValue = reader.IsDBNull(reader.GetOrdinal("DefaultValue")) ? string.Empty : reader.GetString("DefaultValue"),

                        StandardMax = max,
                        StandardMin = min,

                        Unit = reader.IsDBNull(reader.GetOrdinal("Unit")) ? string.Empty : reader.GetString("Unit"),
                    });
                }
            }
            return list;
        }
        public static bool SaveRecordParameters(string name, string reportname, string appname, string desc, int datafrom, string defaultvalue, string standmax, string standmin, string unit)
        {
            try
            {
                string sql2 = $"INSERT INTO recordparameters ( `Name`, `ReportName`, `AppName`,`Desc`, `DataFrom`, `DefaultValue`,  `StandardMax`,  `StandardMin`, `Unit` ) VALUES ('{name}','{reportname}','{appname}','{desc}',{datafrom},'{defaultvalue}','{standmax}','{standmin}','{unit}') ON DUPLICATE KEY UPDATE `ReportName`= '{reportname}',`AppName`='{appname}',`Desc`= '{desc}',`DataFrom`= {datafrom},`DefaultValue`= '{defaultvalue}',`StandardMax`='{standmax}',`StandardMin`= '{standmin}',`Unit`= '{unit}';";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql2);
                return res > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存错误,检查有无重复名称： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        public static bool DeleteRecordParameters(string name)
        {
            try
            {
                string sql2 = $"DELETE FROM `recordparameters` WHERE  `Name`= '{name}'; ";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql2);
                return res > 0;
            }
            catch (Exception ex)
            {
            }
            return false;
        }

        public static bool SaveResultParameters(string oper, string testplanname, string testtemplatename, string testprojectid, string testprojectname, string sn, string times, DateTime dt, string dataname, string datadesc, string datatype, string defaultvalue, string readvalue, string readavg, string readmax, string readmin, string qc, string unit)
        {
            try//testplanname//testtemplatename
            {
                string sql2 = $"INSERT INTO resultparameter ( `oper`,`testplanname`,`testtemplatename`,`testprojectid`,`testprojectname`,`sn`,`times`,`datetime`, `dataname`,`datadesc`, `datatype`, `defaultvalue`, `readvalue`, `readavg`, `readmax` , `readmin` , `qc`, `unit` ) VALUES ('{oper}','{testplanname}','{testtemplatename}','{testprojectid}','{testprojectname}','{sn}','{times}','{dt}','{dataname}','{datadesc}','{datatype}','{defaultvalue}','{readvalue}','{readavg}','{readmax}','{readmin}','{qc}','{unit}') ;";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql2);
                return res > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存错误,检查有无重复名称： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        public static bool SaveResultParameters(string oper, string testprojectid, string testprojectname, string sn, DateTime dt, string dataname, string datadesc, string datatype, string defaultvalue, string readvalue, string qc, string unit)
        {
            try
            {
                string sql2 = $"INSERT INTO resultparameter ( `oper`,`testprojectid`,`testprojectname`,`sn`,`datetime`, `dataname`,`datadesc`, `datatype`, `defaultvalue`, `readvalue`, `readavg`, `readmax` , `readmin` , `qc`, `unit` ) VALUES ('{oper}','{testprojectid}','{testprojectname}','{sn}','{dt}','{dataname}','{datadesc}','{datatype}','{defaultvalue}','{readvalue}','{qc}','{unit}') ;";
                int res = MySqlHelper.ExecuteNonQuery(appconfig.DBConnectionServer, sql2);
                return res > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存错误,检查有无重复名称： {ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return false;
        }
        public static AntList<RecordData> GetResultParameters(string planname, string templatename, string testprojectname, string sn, DateTime? dts, DateTime? dte)
        {
            try
            {
                var list = new AntList<RecordData>();
                string sql = $"SELECT * FROM resultparameter WHERE `testplanname` like '%{planname}%' AND `testtemplatename` like '%{templatename}%' AND  `testprojectname` like '%{testprojectname}%' AND `sn` like '%{sn}%' AND `datetime` >='{dts}' AND `datetime` <= '{dte}' ORDER BY id;";
                using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
                {
                    while (reader.Read())
                    {
                        float.TryParse(reader.IsDBNull(reader.GetOrdinal("readavg")) ? string.Empty : reader.GetString("readavg"), out float readavg);
                        float.TryParse(reader.IsDBNull(reader.GetOrdinal("readmax")) ? string.Empty : reader.GetString("readmax"), out float readmax);
                        float.TryParse(reader.IsDBNull(reader.GetOrdinal("readmin")) ? string.Empty : reader.GetString("readmin"), out float readmin);

                        list.Add(new RecordData
                        {
                            ID = reader.IsDBNull(reader.GetOrdinal("id")) ? 0 : reader.GetInt16("id"),
                            PlanID = reader.IsDBNull(reader.GetOrdinal("testplanname")) ? string.Empty : reader.GetString("testplanname"),
                            PlanName = reader.IsDBNull(reader.GetOrdinal("testplanname")) ? string.Empty : reader.GetString("testplanname"),
                            SubPlanName = reader.IsDBNull(reader.GetOrdinal("testprojectname")) ? string.Empty : reader.GetString("testprojectname"),
                            ProjectID = reader.IsDBNull(reader.GetOrdinal("testprojectid")) ? string.Empty : reader.GetString("testprojectid"),
                            ProjectName = reader.IsDBNull(reader.GetOrdinal("testprojectname")) ? string.Empty : reader.GetString("testprojectname"),
                            ProductSN = reader.IsDBNull(reader.GetOrdinal("sn")) ? string.Empty : reader.GetString("sn"),
                            ProjectDT = reader.IsDBNull(reader.GetOrdinal("datetime")) ? DateTime.MinValue : reader.GetDateTime("datetime"),
                            Name = reader.IsDBNull(reader.GetOrdinal("dataname")) ? string.Empty : reader.GetString("dataname"),
                            DataType = reader.IsDBNull(reader.GetOrdinal("datatype")) ? string.Empty : reader.GetString("datatype"),
                            Desc = reader.IsDBNull(reader.GetOrdinal("datadesc")) ? string.Empty : reader.GetString("datadesc"),
                            QC = reader.IsDBNull(reader.GetOrdinal("qc")) ? string.Empty : reader.GetString("qc"),
                            DefaultValue = reader.IsDBNull(reader.GetOrdinal("defaultvalue")) ? string.Empty : reader.GetString("defaultvalue"),
                            ReadValue = reader.IsDBNull(reader.GetOrdinal("readvalue")) ? string.Empty : reader.GetString("readvalue"),
                            Unit = reader.IsDBNull(reader.GetOrdinal("unit")) ? string.Empty : reader.GetString("unit"),
                            ReadAVG = readavg,
                            ReadMax = readmax,
                            ReadMin = readmin,
                        });
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return null;
        }
        public static AntList<RecordData> GetResultParameters(string planname, string templatename, string sn, DateTime? dts)
        {
            try
            {
                var list = new AntList<RecordData>();
                string sql = $"SELECT * FROM resultparameter WHERE `testplanname` like '%{planname}%' AND `testtemplatename` like '%{templatename}%' AND `sn` like '%{sn}%' AND `datetime` >='{dts}' ORDER BY id;";
                using (MySqlDataReader reader = MySqlHelper.ExecuteReader(appconfig.DBConnectionServer, sql))
                {
                    while (reader.Read())
                    {
                        float.TryParse(reader.IsDBNull(reader.GetOrdinal("readavg")) ? string.Empty : reader.GetString("readavg"), out float readavg);
                        float.TryParse(reader.IsDBNull(reader.GetOrdinal("readmax")) ? string.Empty : reader.GetString("readmax"), out float readmax);
                        float.TryParse(reader.IsDBNull(reader.GetOrdinal("readmin")) ? string.Empty : reader.GetString("readmin"), out float readmin);

                        list.Add(new RecordData
                        {
                            ID = reader.IsDBNull(reader.GetOrdinal("id")) ? 0 : reader.GetInt16("id"),
                            PlanID = reader.IsDBNull(reader.GetOrdinal("testplanname")) ? string.Empty : reader.GetString("testplanname"),
                            PlanName = reader.IsDBNull(reader.GetOrdinal("testplanname")) ? string.Empty : reader.GetString("testplanname"),
                            SubPlanName = reader.IsDBNull(reader.GetOrdinal("testprojectname")) ? string.Empty : reader.GetString("testprojectname"),
                            ProjectID = reader.IsDBNull(reader.GetOrdinal("testprojectid")) ? string.Empty : reader.GetString("testprojectid"),
                            ProjectName = reader.IsDBNull(reader.GetOrdinal("testprojectname")) ? string.Empty : reader.GetString("testprojectname"),
                            ProductSN = reader.IsDBNull(reader.GetOrdinal("sn")) ? string.Empty : reader.GetString("sn"),
                            ProductTimes = reader.IsDBNull(reader.GetOrdinal("times")) ? string.Empty : reader.GetString("times"),
                            ProjectDT = reader.IsDBNull(reader.GetOrdinal("datetime")) ? DateTime.MinValue : reader.GetDateTime("datetime"),
                            Name = reader.IsDBNull(reader.GetOrdinal("dataname")) ? string.Empty : reader.GetString("dataname"),
                            DataType = reader.IsDBNull(reader.GetOrdinal("datatype")) ? string.Empty : reader.GetString("datatype"),
                            Desc = reader.IsDBNull(reader.GetOrdinal("datadesc")) ? string.Empty : reader.GetString("datadesc"),
                            QC = reader.IsDBNull(reader.GetOrdinal("qc")) ? string.Empty : reader.GetString("qc"),
                            DefaultValue = reader.IsDBNull(reader.GetOrdinal("defaultvalue")) ? string.Empty : reader.GetString("defaultvalue"),
                            ReadValue = reader.IsDBNull(reader.GetOrdinal("readvalue")) ? string.Empty : reader.GetString("readvalue"),
                            Unit = reader.IsDBNull(reader.GetOrdinal("unit")) ? string.Empty : reader.GetString("unit"),
                            ReadAVG = readavg,
                            ReadMax = readmax,
                            ReadMin = readmin,
                        });
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex.Message}", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            return null;
        }
    }
}
